/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2023 天天 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.tiantian.mall.service.impl;

import ltd.tiantian.mall.common.*;
import ltd.tiantian.mall.config.ProjectConfig;
import ltd.tiantian.mall.controller.vo.*;
import ltd.tiantian.mall.dao.*;
import ltd.tiantian.mall.entity.*;
import ltd.tiantian.mall.exception.TianTianMallException;
import ltd.tiantian.mall.service.TianTianMallOrderService;
import ltd.tiantian.mall.task.OrderUnPaidTask;
import ltd.tiantian.mall.task.TaskService;
import ltd.tiantian.mall.util.BeanUtil;
import ltd.tiantian.mall.util.NumberUtil;
import ltd.tiantian.mall.util.PageQueryUtil;
import ltd.tiantian.mall.util.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

@Service
public class TianTianMallOrderServiceImpl implements TianTianMallOrderService {

    @Autowired
    private TianTianMallOrderMapper tianTianMallOrderMapper;
    @Autowired
    private TianTianMallOrderItemMapper tianTianMallOrderItemMapper;
    @Autowired
    private TianTianMallShoppingCartItemMapper tianTianMallShoppingCartItemMapper;
    @Autowired
    private TianTianMallGoodsMapper tianTianMallGoodsMapper;
    @Autowired
    private TianTianMallUserCouponRecordMapper tianTianMallUserCouponRecordMapper;
    @Autowired
    private TianTianMallCouponMapper tianTianMallCouponMapper;
    @Autowired
    private TianTianMallSeckillMapper tianTianMallSeckillMapper;
    @Autowired
    private TianTianMallSeckillSuccessMapper tianTianMallSeckillSuccessMapper;
    @Autowired
    private TaskService taskService;

    @Override
    public PageResult<TianTianMallOrder> getTianTianMallOrdersPage(PageQueryUtil pageUtil) {
        int total = tianTianMallOrderMapper.getTotalTianTianMallOrders(pageUtil);
        List<TianTianMallOrder> tianTianMallOrders = tianTianMallOrderMapper.findTianTianMallOrderList(pageUtil);
        return new PageResult<>(tianTianMallOrders, total, pageUtil.getLimit(), pageUtil.getPage());
    }

    @Override
    @Transactional
    public String updateOrderInfo(TianTianMallOrder tianTianMallOrder) {
        TianTianMallOrder temp = tianTianMallOrderMapper.selectByPrimaryKey(tianTianMallOrder.getOrderId());
        // 不为空且orderStatus>=0且状态为出库之前可以修改部分信息
        if (temp != null && temp.getOrderStatus() >= 0 && temp.getOrderStatus() < 3) {
            temp.setTotalPrice(tianTianMallOrder.getTotalPrice());
            temp.setUserAddress(tianTianMallOrder.getUserAddress());
            temp.setUpdateTime(new Date());
            if (tianTianMallOrderMapper.updateByPrimaryKeySelective(temp) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            }
            return ServiceResultEnum.DB_ERROR.getResult();
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public boolean updateByPrimaryKeySelective(TianTianMallOrder tianTianMallOrder) {
        return tianTianMallOrderMapper.updateByPrimaryKeySelective(tianTianMallOrder) > 0;
    }

    @Override
    @Transactional
    public String checkDone(Long[] ids) {
        // 查询所有的订单 判断状态 修改状态和更新时间
        List<TianTianMallOrder> orders = tianTianMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
        StringBuilder errorOrderNos = new StringBuilder();
        if (!CollectionUtils.isEmpty(orders)) {
            for (TianTianMallOrder tianTianMallOrder : orders) {
                if (tianTianMallOrder.getIsDeleted() == 1) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                    continue;
                }
                if (tianTianMallOrder.getOrderStatus() != 1) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                }
            }
            if (StringUtils.isEmpty(errorOrderNos.toString())) {
                // 订单状态正常 可以执行配货完成操作 修改订单状态和更新时间
                if (tianTianMallOrderMapper.checkDone(Arrays.asList(ids)) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                // 订单此时不可执行出库操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功的订单，无法执行配货完成操作";
                }
            }
        }
        // 未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String checkOut(Long[] ids) {
        // 查询所有的订单 判断状态 修改状态和更新时间
        List<TianTianMallOrder> orders = tianTianMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
        StringBuilder errorOrderNos = new StringBuilder();
        if (!CollectionUtils.isEmpty(orders)) {
            for (TianTianMallOrder tianTianMallOrder : orders) {
                if (tianTianMallOrder.getIsDeleted() == 1) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                    continue;
                }
                if (tianTianMallOrder.getOrderStatus() != 1 && tianTianMallOrder.getOrderStatus() != 2) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                }
            }
            if (StringUtils.isEmpty(errorOrderNos.toString())) {
                // 订单状态正常 可以执行出库操作 修改订单状态和更新时间
                if (tianTianMallOrderMapper.checkOut(Arrays.asList(ids)) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                // 订单此时不可执行出库操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功或配货完成无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功或配货完成的订单，无法执行出库操作";
                }
            }
        }
        // 未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String closeOrder(Long[] ids) {
        // 查询所有的订单 判断状态 修改状态和更新时间
        List<TianTianMallOrder> orders = tianTianMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
        StringBuilder errorOrderNos = new StringBuilder();
        if (!CollectionUtils.isEmpty(orders)) {
            for (TianTianMallOrder tianTianMallOrder : orders) {
                // isDeleted=1 一定为已关闭订单
                if (tianTianMallOrder.getIsDeleted() == 1) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                    continue;
                }
                // 已关闭或者已完成无法关闭订单
                if (tianTianMallOrder.getOrderStatus() == 4 || tianTianMallOrder.getOrderStatus() < 0) {
                    errorOrderNos.append(tianTianMallOrder.getOrderNo()).append(" ");
                }
            }
            if (StringUtils.isEmpty(errorOrderNos.toString())) {
                // 订单状态正常 可以执行关闭操作 修改订单状态和更新时间
                if (tianTianMallOrderMapper.closeOrder(Arrays.asList(ids), TianTianMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                // 订单此时不可执行关闭操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单不能执行关闭操作";
                } else {
                    return "你选择的订单不能执行关闭操作";
                }
            }
        }
        // 未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveOrder(TianTianMallUserVO user, Long couponUserId, List<TianTianMallShoppingCartItemVO> myShoppingCartItems) {
        List<Long> itemIdList = myShoppingCartItems.stream().map(TianTianMallShoppingCartItemVO::getCartItemId).collect(Collectors.toList());
        List<Long> goodsIds = myShoppingCartItems.stream().map(TianTianMallShoppingCartItemVO::getGoodsId).collect(Collectors.toList());
        List<TianTianMallGoods> tianTianMallGoods = tianTianMallGoodsMapper.selectByPrimaryKeys(goodsIds);
        // 检查是否包含已下架商品
        List<TianTianMallGoods> goodsListNotSelling = tianTianMallGoods.stream()
                .filter(tianTianMallGoodsTemp -> tianTianMallGoodsTemp.getGoodsSellStatus() != Constants.SELL_STATUS_UP)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(goodsListNotSelling)) {
            // goodsListNotSelling 对象非空则表示有下架商品
            TianTianMallException.fail(goodsListNotSelling.get(0).getGoodsName() + "已下架，无法生成订单");
        }
        Map<Long, TianTianMallGoods> tianTianMallGoodsMap = tianTianMallGoods.stream().collect(Collectors.toMap(TianTianMallGoods::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));
        // 判断商品库存
        for (TianTianMallShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
            // 查出的商品中不存在购物车中的这条关联商品数据，直接返回错误提醒
            if (!tianTianMallGoodsMap.containsKey(shoppingCartItemVO.getGoodsId())) {
                TianTianMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
            }
            // 存在数量大于库存的情况，直接返回错误提醒
            if (shoppingCartItemVO.getGoodsCount() > tianTianMallGoodsMap.get(shoppingCartItemVO.getGoodsId()).getStockNum()) {
                TianTianMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
            }
        }
        if (CollectionUtils.isEmpty(itemIdList) || CollectionUtils.isEmpty(goodsIds) || CollectionUtils.isEmpty(tianTianMallGoods)) {
            TianTianMallException.fail(ServiceResultEnum.ORDER_GENERATE_ERROR.getResult());
        }
        if (tianTianMallShoppingCartItemMapper.deleteBatch(itemIdList) <= 0) {
            TianTianMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
        }
        List<StockNumDTO> stockNumDTOS = BeanUtil.copyList(myShoppingCartItems, StockNumDTO.class);
        int updateStockNumResult = tianTianMallGoodsMapper.updateStockNum(stockNumDTOS);
        if (updateStockNumResult < 1) {
            TianTianMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
        }
        // 生成订单号
        String orderNo = NumberUtil.genOrderNo();
        int priceTotal = 0;
        // 保存订单
        TianTianMallOrder tianTianMallOrder = new TianTianMallOrder();
        tianTianMallOrder.setOrderNo(orderNo);
        tianTianMallOrder.setUserId(user.getUserId());
        tianTianMallOrder.setUserAddress(user.getAddress());
        // 总价
        for (TianTianMallShoppingCartItemVO tianTianMallShoppingCartItemVO : myShoppingCartItems) {
            priceTotal += tianTianMallShoppingCartItemVO.getGoodsCount() * tianTianMallShoppingCartItemVO.getSellingPrice();
        }
        // 如果使用了优惠券
        if (couponUserId != null) {
            TianTianMallUserCouponRecord tianTianMallUserCouponRecord = tianTianMallUserCouponRecordMapper.selectByPrimaryKey(couponUserId);
            Long userId = tianTianMallUserCouponRecord.getUserId();
            if (!Objects.equals(userId, user.getUserId())) {
                TianTianMallException.fail("优惠卷所属用户与当前用户不一致！");
            }
            Long couponId = tianTianMallUserCouponRecord.getCouponId();
            TianTianMallCoupon tianTianMallCoupon = tianTianMallCouponMapper.selectByPrimaryKey(couponId);
            priceTotal -= tianTianMallCoupon.getDiscount();
        }
        if (priceTotal < 1) {
            TianTianMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
        }
        tianTianMallOrder.setTotalPrice(priceTotal);
        String extraInfo = "tiantianmall-plus支付宝沙箱支付";
        tianTianMallOrder.setExtraInfo(extraInfo);
        // 生成订单项并保存订单项纪录
        if (tianTianMallOrderMapper.insertSelective(tianTianMallOrder) <= 0) {
            TianTianMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
        }
        // 如果使用了优惠券，则更新优惠券状态
        if (couponUserId != null) {
            TianTianMallUserCouponRecord couponUser = new TianTianMallUserCouponRecord();
            couponUser.setCouponUserId(couponUserId);
            couponUser.setOrderId(tianTianMallOrder.getOrderId());
            couponUser.setUseStatus((byte) 1);
            couponUser.setUsedTime(new Date());
            couponUser.setUpdateTime(new Date());
            tianTianMallUserCouponRecordMapper.updateByPrimaryKeySelective(couponUser);
        }
        // 生成所有的订单项快照，并保存至数据库
        List<TianTianMallOrderItem> tianTianMallOrderItems = new ArrayList<>();
        for (TianTianMallShoppingCartItemVO tianTianMallShoppingCartItemVO : myShoppingCartItems) {
            TianTianMallOrderItem tianTianMallOrderItem = new TianTianMallOrderItem();
            // 使用BeanUtil工具类将tianTianMallShoppingCartItemVO中的属性复制到tianTianMallOrderItem对象中
            BeanUtil.copyProperties(tianTianMallShoppingCartItemVO, tianTianMallOrderItem);
            // TianTianMallOrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
            tianTianMallOrderItem.setOrderId(tianTianMallOrder.getOrderId());
            tianTianMallOrderItems.add(tianTianMallOrderItem);
        }
        // 保存至数据库
        if (tianTianMallOrderItemMapper.insertBatch(tianTianMallOrderItems) <= 0) {
            TianTianMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
        }
        // 订单支付超期任务，超过300秒自动取消订单
        taskService.addTask(new OrderUnPaidTask(tianTianMallOrder.getOrderId(), ProjectConfig.getOrderUnpaidOverTime() * 1000));
        // 所有操作成功后，将订单号返回，以供Controller方法跳转到订单详情
        return orderNo;
    }

    @Override
    public String seckillSaveOrder(Long seckillSuccessId, Long userId) {
        TianTianMallSeckillSuccess tianTianMallSeckillSuccess = tianTianMallSeckillSuccessMapper.selectByPrimaryKey(seckillSuccessId);
        if (!tianTianMallSeckillSuccess.getUserId().equals(userId)) {
            throw new TianTianMallException("当前登陆用户与抢购秒杀商品的用户不匹配");
        }
        Long seckillId = tianTianMallSeckillSuccess.getSeckillId();
        TianTianMallSeckill tianTianMallSeckill = tianTianMallSeckillMapper.selectByPrimaryKey(seckillId);
        Long goodsId = tianTianMallSeckill.getGoodsId();
        TianTianMallGoods tianTianMallGoods = tianTianMallGoodsMapper.selectByPrimaryKey(goodsId);
        // 生成订单号
        String orderNo = NumberUtil.genOrderNo();
        // 保存订单
        TianTianMallOrder tianTianMallOrder = new TianTianMallOrder();
        tianTianMallOrder.setOrderNo(orderNo);
        tianTianMallOrder.setTotalPrice(tianTianMallSeckill.getSeckillPrice());
        tianTianMallOrder.setUserId(userId);
        tianTianMallOrder.setUserAddress("秒杀测试地址");
        tianTianMallOrder.setOrderStatus((byte) TianTianMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus());
        tianTianMallOrder.setPayStatus((byte) PayStatusEnum.PAY_ING.getPayStatus());
        tianTianMallOrder.setPayType((byte) PayTypeEnum.NOT_PAY.getPayType());
        tianTianMallOrder.setPayTime(null);
        String extraInfo = "";
        tianTianMallOrder.setExtraInfo(extraInfo);
        if (tianTianMallOrderMapper.insertSelective(tianTianMallOrder) <= 0) {
            throw new TianTianMallException("生成订单内部异常");
        }
        // 保存订单商品项
        TianTianMallOrderItem tianTianMallOrderItem = new TianTianMallOrderItem();
        Long orderId = tianTianMallOrder.getOrderId();
        tianTianMallOrderItem.setOrderId(orderId);
        tianTianMallOrderItem.setSeckillId(seckillId);
        tianTianMallOrderItem.setGoodsId(tianTianMallGoods.getGoodsId());
        tianTianMallOrderItem.setGoodsCoverImg(tianTianMallGoods.getGoodsCoverImg());
        tianTianMallOrderItem.setGoodsName(tianTianMallGoods.getGoodsName());
        tianTianMallOrderItem.setGoodsCount(1);
        tianTianMallOrderItem.setSellingPrice(tianTianMallSeckill.getSeckillPrice());
        if (tianTianMallOrderItemMapper.insert(tianTianMallOrderItem) <= 0) {
            throw new TianTianMallException("生成订单内部异常");
        }
        // 订单支付超期任务
        taskService.addTask(new OrderUnPaidTask(tianTianMallOrder.getOrderId(), 30 * 1000));
        return orderNo;
    }

    @Override
    public TianTianMallOrderDetailVO getOrderDetailByOrderNo(String orderNo, Long userId) {
        TianTianMallOrder tianTianMallOrder = tianTianMallOrderMapper.selectByOrderNo(orderNo);
        if (tianTianMallOrder == null) {
            TianTianMallException.fail(ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult());
        }
        //验证是否是当前userId下的订单，否则报错
        if (!userId.equals(tianTianMallOrder.getUserId())) {
            TianTianMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
        }
        List<TianTianMallOrderItem> orderItems = tianTianMallOrderItemMapper.selectByOrderId(tianTianMallOrder.getOrderId());
        //获取订单项数据
        if (CollectionUtils.isEmpty(orderItems)) {
            TianTianMallException.fail(ServiceResultEnum.ORDER_ITEM_NOT_EXIST_ERROR.getResult());
        }
        List<TianTianMallOrderItemVO> tianTianMallOrderItemVOS = BeanUtil.copyList(orderItems, TianTianMallOrderItemVO.class);
        TianTianMallOrderDetailVO tianTianMallOrderDetailVO = new TianTianMallOrderDetailVO();
        BeanUtil.copyProperties(tianTianMallOrder, tianTianMallOrderDetailVO);
        tianTianMallOrderDetailVO.setOrderStatusString(TianTianMallOrderStatusEnum.getTianTianMallOrderStatusEnumByStatus(tianTianMallOrderDetailVO.getOrderStatus()).getName());
        tianTianMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(tianTianMallOrderDetailVO.getPayType()).getName());
        tianTianMallOrderDetailVO.setTianTianMallOrderItemVOS(tianTianMallOrderItemVOS);
        return tianTianMallOrderDetailVO;
    }

    @Override
    public TianTianMallOrder getTianTianMallOrderByOrderNo(String orderNo) {
        return tianTianMallOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public PageResult getMyOrders(PageQueryUtil pageUtil) {
        int total = tianTianMallOrderMapper.getTotalTianTianMallOrders(pageUtil);
        List<TianTianMallOrderListVO> orderListVOS = new ArrayList<>();
        if (total > 0) {
            List<TianTianMallOrder> tianTianMallOrders = tianTianMallOrderMapper.findTianTianMallOrderList(pageUtil);
            // 数据转换 将实体类转成vo
            orderListVOS = BeanUtil.copyList(tianTianMallOrders, TianTianMallOrderListVO.class);
            // 设置订单状态中文显示值
            for (TianTianMallOrderListVO tianTianMallOrderListVO : orderListVOS) {
                tianTianMallOrderListVO.setOrderStatusString(TianTianMallOrderStatusEnum.getTianTianMallOrderStatusEnumByStatus(tianTianMallOrderListVO.getOrderStatus()).getName());
            }
            List<Long> orderIds = tianTianMallOrders.stream().map(TianTianMallOrder::getOrderId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderIds)) {
                List<TianTianMallOrderItem> orderItems = tianTianMallOrderItemMapper.selectByOrderIds(orderIds);
                Map<Long, List<TianTianMallOrderItem>> itemByOrderIdMap = orderItems.stream().collect(groupingBy(TianTianMallOrderItem::getOrderId));
                for (TianTianMallOrderListVO tianTianMallOrderListVO : orderListVOS) {
                    // 封装每个订单列表对象的订单项数据
                    if (itemByOrderIdMap.containsKey(tianTianMallOrderListVO.getOrderId())) {
                        List<TianTianMallOrderItem> orderItemListTemp = itemByOrderIdMap.get(tianTianMallOrderListVO.getOrderId());
                        // 将TianTianMallOrderItem对象列表转换成TianTianMallOrderItemVO对象列表
                        List<TianTianMallOrderItemVO> tianTianMallOrderItemVOS = BeanUtil.copyList(orderItemListTemp, TianTianMallOrderItemVO.class);
                        tianTianMallOrderListVO.setTianTianMallOrderItemVOS(tianTianMallOrderItemVOS);
                    }
                }
            }
        }
        return new PageResult(orderListVOS, total, pageUtil.getLimit(), pageUtil.getPage());
    }

    @Override
    public String cancelOrder(String orderNo, Long userId) {
        TianTianMallOrder tianTianMallOrder = tianTianMallOrderMapper.selectByOrderNo(orderNo);
        if (tianTianMallOrder != null) {
            // 验证是否是当前userId下的订单，否则报错
            if (!userId.equals(tianTianMallOrder.getUserId())) {
                TianTianMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
            }
            // 订单状态判断
            if (tianTianMallOrder.getOrderStatus().intValue() == TianTianMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus()
                    || tianTianMallOrder.getOrderStatus().intValue() == TianTianMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()
                    || tianTianMallOrder.getOrderStatus().intValue() == TianTianMallOrderStatusEnum.ORDER_CLOSED_BY_EXPIRED.getOrderStatus()
                    || tianTianMallOrder.getOrderStatus().intValue() == TianTianMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            if (tianTianMallOrderMapper.closeOrder(Collections.singletonList(tianTianMallOrder.getOrderId()), TianTianMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String finishOrder(String orderNo, Long userId) {
        TianTianMallOrder tianTianMallOrder = tianTianMallOrderMapper.selectByOrderNo(orderNo);
        if (tianTianMallOrder != null) {
            // 验证是否是当前userId下的订单，否则报错
            if (!userId.equals(tianTianMallOrder.getUserId())) {
                return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
            }
            // 订单状态判断 非出库状态下不进行修改操作
            if (tianTianMallOrder.getOrderStatus().intValue() != TianTianMallOrderStatusEnum.ORDER_EXPRESS.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            tianTianMallOrder.setOrderStatus((byte) TianTianMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus());
            tianTianMallOrder.setUpdateTime(new Date());
            if (tianTianMallOrderMapper.updateByPrimaryKeySelective(tianTianMallOrder) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String paySuccess(String orderNo, int payType) {
        TianTianMallOrder tianTianMallOrder = tianTianMallOrderMapper.selectByOrderNo(orderNo);
        if (tianTianMallOrder == null) {
            return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
        }
        // 订单状态判断 非待支付状态下不进行修改操作
        if (tianTianMallOrder.getOrderStatus().intValue() != TianTianMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
            return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
        }
        tianTianMallOrder.setOrderStatus((byte) TianTianMallOrderStatusEnum.ORDER_PAID.getOrderStatus());
        tianTianMallOrder.setPayType((byte) payType);
        tianTianMallOrder.setPayStatus((byte) PayStatusEnum.PAY_SUCCESS.getPayStatus());
        tianTianMallOrder.setPayTime(new Date());
        tianTianMallOrder.setUpdateTime(new Date());
        if (tianTianMallOrderMapper.updateByPrimaryKeySelective(tianTianMallOrder) <= 0) {
            return ServiceResultEnum.DB_ERROR.getResult();
        }
        taskService.removeTask(new OrderUnPaidTask(tianTianMallOrder.getOrderId()));
        return ServiceResultEnum.SUCCESS.getResult();
    }

    @Override
    public List<TianTianMallOrderItemVO> getOrderItems(Long id) {
        TianTianMallOrder tianTianMallOrder = tianTianMallOrderMapper.selectByPrimaryKey(id);
        if (tianTianMallOrder != null) {
            List<TianTianMallOrderItem> orderItems = tianTianMallOrderItemMapper.selectByOrderId(tianTianMallOrder.getOrderId());
            // 获取订单项数据
            if (!CollectionUtils.isEmpty(orderItems)) {
                return BeanUtil.copyList(orderItems, TianTianMallOrderItemVO.class);
            }
        }
        return null;
    }
}
